package jp.dev7.hongo2.controller.admin.question;

import jp.dev7.hongo2.model.Question;
import jp.dev7.hongo2.service.QuestionService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.MaxlengthValidator;
import org.slim3.controller.validator.RequiredValidator;
import org.slim3.controller.validator.Validators;
import org.slim3.util.BeanUtil;
import org.slim3.util.Converter;
import org.slim3.util.CopyOptions;

import com.google.appengine.api.datastore.Text;
import com.google.appengine.repackaged.com.google.common.collect.Lists;

public class CreatePostController extends Controller {

    private QuestionService questionService = new QuestionService();

    @Override
    public Navigation run() throws Exception {

        Validators v = new Validators(request);
        v.add(
            "content",
            RequiredValidator.INSTANCE,
            new MaxlengthValidator(140));
        if (!v.validate()) {
            return forward("create.jsp");
        }

        Question q = new Question();
        CopyOptions opt = new CopyOptions();
        opt.converter(new Converter<Text>() {

            public String getAsString(Object value) {
                if (value == null || value instanceof Text == false) {
                    return "";
                }
                return ((Text) value).getValue();
            }

            public Text getAsObject(String value) {
                return new Text(value);
            }

            public boolean isTarget(Class<?> clazz) {
                return Text.class == clazz;
            }

        }, "content");
        BeanUtil.copy(request, q, opt);

        questionService.create(q);

        requestScope("message", Lists.newArrayList("保存しました"));
        return forward("create");
    }
}
